<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>最简WebSocket测试</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        margin: 20px;
      }
      #log {
        background: #f0f0f0;
        padding: 10px;
        height: 400px;
        overflow-y: scroll;
      }
      .success {
        color: green;
      }
      .error {
        color: red;
      }
      .info {
        color: blue;
      }
    </style>
  </head>
  <body>
    <h1>最简WebSocket连接测试</h1>
    <button onclick="connect()">连接</button>
    <button onclick="disconnect()">断开</button>
    <button onclick="sendTest()">发送测试</button>
    <div id="log"></div>

    <script>
      let ws = null;
      const log = document.getElementById("log");

      function addLog(message, className = "") {
        const div = document.createElement("div");
        div.className = className;
        div.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
        log.appendChild(div);
        log.scrollTop = log.scrollHeight;
        console.log(message);
      }

      function connect() {
        if (ws) {
          addLog("关闭现有连接...", "info");
          ws.close();
        }

        addLog("开始连接到 ws://localhost:3001/ws...", "info");

        ws = new WebSocket("ws://localhost:3001/ws");

        ws.onopen = (event) => {
          addLog("✅ 连接成功！readyState: " + ws.readyState, "success");
        };

        ws.onmessage = (event) => {
          addLog("📩 收到消息: " + event.data, "success");
        };

        ws.onclose = (event) => {
          addLog(
            `❌ 连接关闭: 代码=${event.code}, 原因="${event.reason}", wasClean=${event.wasClean}`,
            "error"
          );
        };

        ws.onerror = (event) => {
          addLog("💥 连接错误发生", "error");
          console.error("WebSocket错误:", event);
        };
      }

      function disconnect() {
        if (ws) {
          addLog("主动断开连接...", "info");
          ws.close(1000, "用户主动断开");
        } else {
          addLog("没有活动连接", "error");
        }
      }

      function sendTest() {
        if (ws && ws.readyState === WebSocket.OPEN) {
          const message = {
            type: "test",
            message: "Hello from client",
            timestamp: new Date().toISOString(),
          };
          ws.send(JSON.stringify(message));
          addLog("📤 发送消息: " + JSON.stringify(message), "info");
        } else {
          addLog("连接未就绪，状态: " + (ws ? ws.readyState : "null"), "error");
        }
      }

      // 页面加载时自动连接
      window.onload = () => {
        addLog("页面加载完成，准备测试连接");
      };
    </script>
  </body>
</html>
